package com.dianrui.moonfire.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;


import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.adapter.MessageAdapter;
import com.dianrui.moonfire.bean.MessageModel;
import com.dianrui.moonfire.util.EventBusConstants;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.dianrui.moonfire.view.SwipeMenuLayout;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:我的消息
 * User: luoziyin
 * Date: 2020-8-17
 */
@SuppressWarnings("ALL")
public class MessageActivity extends BaseActivity {
    private int mPageIndex = 1;
    private List<MessageModel> mMessageList = new ArrayList<>();
    private MessageAdapter messageAdapter;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    @Override
    public int getContentViewId() {
        return R.layout.activity_message;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        customInit(true);
        title.setText("我的消息");
        getMsgList(false);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MessageActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        messageAdapter = new MessageAdapter(R.layout.item_message, mMessageList,MessageActivity.this);
        recyclerView.setAdapter(messageAdapter);

        refreshLayout.setOnRefreshLoadMoreListener(loadMoreListener);

        resetRefresh();

        messageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MessageModel messageModel = mMessageList.get(position);
                if (messageModel != null) {
                    switch (view.getId()){
                        case R.id.click_message:
                            SwipeMenuLayout layout= (SwipeMenuLayout) view.getParent();
                            TextView title=layout.findViewById(R.id.title);
                            TextView time=layout.findViewById(R.id.time);
                            TextView content=layout.findViewById(R.id.content);
                            TextView msg_show_red_dot=layout.findViewById(R.id.msg_show_red_dot);
                            ImageView msg_img=layout.findViewById(R.id.msg_img);

                            if (!layout.isExpand) {
                                readSystemMessage(messageModel.messages_id,title,time,content,msg_show_red_dot,msg_img);
                                Intent intent=new Intent(MessageActivity.this, MessageDeatilsActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("id", messageModel.messages_id);
                                intent.putExtras(bundle);
                                startActivity(intent);
                            }else {
                                layout.smoothClose();
                            }
                            break;

                        case R.id.delete:
                            delMessage(messageModel.messages_id,position);
                            break;

                        default:
                            break;
                    }

                }


            }
        });
        messageAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.click_message:
                        SwipeMenuLayout layout= (SwipeMenuLayout) view.getParent();
                        layout.smoothExpand();
                        break;
                }
                return true;
            }
        });

    }


    @Override
    public void initData() {}

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String str) {
        if(TextUtils.equals(str, EventBusConstants.REFRESH_MSG_LIST)) {
            getMsgList(true);
        }
    }


    OnRefreshLoadMoreListener loadMoreListener = new OnRefreshLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            mPageIndex++;
            getMsgList(false);
        }

        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            mPageIndex = 1;
            getMsgList(true);

        }
    };


    private void resetRefresh() {
        mPageIndex = 1;
        refreshLayout.setEnableLoadMore(true);
    }

    private void finishRefresh() {
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();//停止刷新
        } else {
            refreshLayout.finishLoadMore();
        }
    }


    public void getMsgList(final boolean isRfresh) {
        if (isRfresh) {
            mPageIndex = 1;
        }
        JsonObject jsonObject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        jsonObject.addProperty("p", mPageIndex);
        XHttpRequest.getInstance().postRequests(Url.MESSGAE, jsonObject.toString(),new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) throws JSONException {
                finishRefresh();
                if (isRfresh) {
                    mMessageList.clear();
                }
                if (!StringUtils.isEmpty(result)) {
                        if (isFinishing()) {
                            return;
                        }
                        String status= JsonUtils.getJsonStr(result,Constant.STATUS);
                        if (Constant.DATASUCCESS.equals(status)) {
                            String data=JsonUtils.getJsonStr(result,"data");
                            if (!StringUtils.isEmpty(data)) {
                                List<MessageModel> msglist=JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<MessageModel>>(){}.getType());
                                if (msglist != null && msglist.size()>0) {
                                    mMessageList.addAll(msglist);
                                    messageAdapter.setNewData(mMessageList);
                                    refreshLayout.setNoMoreData(false);
                                }else {
                                    messageAdapter.getData().clear();
                                    messageAdapter.setEmptyView(LayoutInflater.from(MessageActivity.this).inflate(R.layout.empty_view,null));
                                    messageAdapter.notifyDataSetChanged();
                                    ToastUtil.showToast(getString(R.string.no_data));
                                }
                            }
                        }else {
                            finishRefresh();
                        }

                    if (mMessageList.size() <= 0) {
                        messageAdapter.getData().clear();
                        messageAdapter.setEmptyView(LayoutInflater.from(MessageActivity.this).inflate(R.layout.empty_view,null));
                        messageAdapter.notifyDataSetChanged();
                    } else {
                        recyclerView.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                finishRefresh();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    @OnClick(R.id.back)
    public void onViewClicked() {
        EventBus.getDefault().post(EventBusConstants.REFRESH_UNREAD_MSG);
        finish();
    }

    //点击消息发动已读
    private void readSystemMessage(String id, final TextView title, final TextView time, final TextView content, final TextView msg_show_red_dot, final ImageView msgDot) {
        JsonObject readmsgJsonobject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            readmsgJsonobject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        readmsgJsonobject.addProperty("messages_id", id);
        XHttpRequest.getInstance().postRequests(Url.READMESSAGE, readmsgJsonobject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                title.setTextColor(getResources().getColor(R.color.nav_color_txt));
                                time.setTextColor(getResources().getColor(R.color.nav_color_txt));
                                content.setTextColor(getResources().getColor(R.color.nav_color_txt));
                                msg_show_red_dot.setVisibility(View.INVISIBLE);
                                msgDot.setAlpha(0.7f);
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //删除消息
    private void delMessage(String messageId, final int position) {
        JsonObject delmsg = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            delmsg.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        delmsg.addProperty("messages_id", messageId);
        XHttpRequest.getInstance().postRequests(Url.DELMESSGAE, delmsg.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {

                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                messageAdapter.getData().remove(position);
                                messageAdapter.notifyDataSetChanged();
                                getMsgList(true);

                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else {
                                //ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            EventBus.getDefault().post(EventBusConstants.REFRESH_UNREAD_MSG);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
